package com.example.myapplication.ui.fragments;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.myapplication.databinding.FragmentOrmLite2Binding;
import com.example.myapplication.mormlite.dao.UserDao;
import com.example.myapplication.mormlite.pojo.UserBean;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.fragment.app.Fragment;

public class OrmLiteFragment extends Fragment {
    private static final String TAG = "OrmLiteFragment";

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private FragmentOrmLite2Binding binding;

    private final ExecutorService executorService = Executors.newFixedThreadPool(2);

    //RomLite
    private volatile UserDao userDao;

    private int num ;

    public OrmLiteFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment OrmLiteFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static OrmLiteFragment newInstance(String param1, String param2) {
        OrmLiteFragment fragment = new OrmLiteFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentOrmLite2Binding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        userDao = new UserDao(requireActivity().getApplication());

        binding.btns.insert.setOnClickListener(v -> {

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    List<UserBean> userBeans = new ArrayList<>();
                    for (int i = 0; i < 100000; i++) {
                        UserBean dasda = new UserBean("name" + i);
                        userBeans.add(dasda);
                    }
                    long startTime = System.currentTimeMillis();
                    userDao.insertList(userBeans);
                    long endTime = (System.currentTimeMillis() - startTime);
                    Log.e(TAG, "OrmLite插入10w数据耗时---->" + endTime + "ms");
                    addView("OrmLite插入10w耗时："+endTime+"ms");
                }
            });
        });


        binding.btns.delete.setOnClickListener(v -> {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    UserBean name = new UserBean("name");
                    name.setId(num);
                    long startTime = System.currentTimeMillis();
                    userDao.delete(name);
                    long endTime = (System.currentTimeMillis() - startTime);
                    Log.e(TAG, "OrmLite删除一条数据耗时---->" + endTime + "ms");
                    addView("OrmLite删除一条耗时："+endTime+"ms");
                }
            });
        });

        binding.btns.update.setOnClickListener(v -> {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    UserBean name = new UserBean("name");
                    name.setId(num);
                    long startTime = System.currentTimeMillis();
                    userDao.update(name);
                    long endTime = (System.currentTimeMillis() - startTime);
                    Log.e(TAG, "OrmLite更新一条数据耗时---->" + endTime + "ms");
                    addView("OrmLite更新一条耗时："+endTime+"ms");
                }
            });
        });

        binding.btns.query.setOnClickListener(v -> {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long startTime = System.currentTimeMillis();
                    userDao.selectAll();
                    long endTime = (System.currentTimeMillis() - startTime);
                    Log.e(TAG, "OrmLite查询所有数据耗时---->" + endTime + "ms");
                    addView("OrmLite查询所有耗时："+endTime+"ms");
                }
            });
        });

        binding.edtInput.input.addTextChangedListener(new TextWatcher() {
            boolean isEdt;
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (isEdt)return;
                isEdt = true;
                String str =editable.toString().replace("/^0*/g", "");
                if (!str.equals("")){
                    int i = Integer.parseInt(str);
                    if (i != 0) num = i;
                }
                isEdt = false;
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (binding != null)
            binding = null;
        if (executorService!=null)executorService.shutdown();
    }

    private void addView(String string) {
        requireActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView textView = new TextView(requireActivity());
                textView.setText(string);
                textView.setTextSize(20);
                ((LinearLayoutCompat) binding.texts.textss).addView(textView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            }
        });
    }
}